package com.d3works.base.service.ical;

import com.d3works.apps.base.db.ICalendarEvent;
import com.d3works.apps.base.db.ICalendarUser;
import com.d3works.apps.base.ical.ICalendarException;
import com.d3works.apps.message.db.EmailAddress;
import com.d3works.auth.db.repo.UserRepository;
import com.d3works.exception.D3worksException;
import com.google.inject.Inject;
import java.io.IOException;
import java.text.ParseException;
import java.util.List;
import javax.mail.MessagingException;

public class ICalendarEventServiceImpl implements ICalendarEventService {

  @Inject protected UserRepository userRepository;

  @Override
  public List<ICalendarUser> addEmailGuest(EmailAddress email, ICalendarEvent event)
      throws ClassNotFoundException, InstantiationException, IllegalAccessException,
          D3worksException, MessagingException, IOException, ICalendarException, ParseException {
    if (email != null) {
      if (event.getAttendees() == null
          || !event.getAttendees().stream()
              .anyMatch(x -> email.getAddress().equals(x.getEmail()))) {
        ICalendarUser calUser = new ICalendarUser();
        calUser.setEmail(email.getAddress());
        calUser.setName(email.getName());
        if (email.getPartner() != null) {
          calUser.setUser(
              userRepository
                  .all()
                  .filter("self.partner.id = ?1", email.getPartner().getId())
                  .fetchOne());
        }
        event.addAttendee(calUser);
      }
    }
    return event.getAttendees();
  }
}
